﻿using Models;
using Newtonsoft.Json;
using SIE.SCADA.Common.Log;
using SIE.SCADA.Helper;
using SIE.SCADA.SqlSugar;
using SIE.SCADA.ZemtDemo;
using SIE.SCADA.ZemtDemo.Common;
using SIE.SCADA.ZemtDemo.MqClient;
using SIE.SCADA.ZemtDemo.MqClient.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;

namespace SCADA_DAQ.ZEMT.Server
{
    /// <summary>
    /// 配置上传
    /// </summary>
    public class EquipManager : MqMangerBase<EquipManager>
    {
        public string CurMatid { get; set; }
        public string line_names = Env.LineName.Value;
        public string LineGroupName = Env.LineGroupName.Value;
        //public event EventHandler MatcfgHandler;
        private readonly string IfaceName = "GETEQUIINFO"; //接口名称
        private readonly string EXCHANAGE = "ZEMT_MQ_EXCHANGE_GETEQUIINFO";
        private readonly string ROUTEKEY = "GETEQUIINFO_SIE";
        //private AdvancedThread _thread;

        public EquipManager()
        {
           
        }

        private void TestMethod()
        {
            Request("GZ0000027740","");
        }

        //配置上传
        void Send(EquipRoot request,string line_name)
        {
            var res = mqhelper.TopicExchangePublish(request, EXCHANAGE, "", $"{IfaceName}.{LineGroupName}"
                , true, false, true, false);
            if (res.Success)
            {
                System.Diagnostics.Debug.WriteLine("数据已推送完成的！");
            }
            else
                System.Diagnostics.Debug.WriteLine("数据推送失败！\n" + res.Message);
        }

        public void Request(string matid,string line_name)
        {
            if (string.IsNullOrEmpty(matid)) return;
            var equip = new Equip() { EQUNR = matid };
            List<Equip> EQUILIST = new List<Equip>();
            EQUILIST.Add(equip);
            EquipRoot equipRoot = new EquipRoot() { EQUILIST = EQUILIST };
            Send(equipRoot, line_name);
        }

        


        public override void Start()
        {
            //Loop();
            Logger.Info("..............................");
            Logger.Info("自动获取设备开始..............................");
            Logger.Info("..............................");
            DataReceive();
            //TestMethod();
#if DEBUG
            RevceiveTest();
#endif
            //base.Start();
        }

        void DataReceive()
        {
              
                var res1 = mqhelper.TopicExchangeConsumer<EquRoot>((data) =>
                {
                    if (data.retcode.Equals("1"))
                    {
                        SaveEqument(data);
                        System.Diagnostics.Trace.WriteLine("配置结果接收成功");
                    }
                    return true;
                }, EXCHANAGE, $"ZEMT_MQ_SIE_{IfaceName}.{LineGroupName}", $"{ROUTEKEY}.{LineGroupName}", true, false, true, false);

        }

        void SaveEqument(EquRoot data)
        {
            Logger.Info("从MES收到设备消息！");
            if (data != null)
            {
                foreach (var pmdatas in data?.EQUIDatas)
                {
                    using (var ctx = pgsql.GetClient())
                    {
                        foreach (var item in pmdatas.EQUIItems)
                        {
                            try
                            {
                                if (pgsql.DBClient is SmdcOrmClient ormClient)
                                {
                                    var equipment = ormClient.SqlSugarClient.Queryable<scada_equipment>().Where(m => m.equipmentid == item.EQUNR).First();
                                    if (equipment != null)
                                    {
                                        equipment.state = item.ZZTBH;
                                        equipment.plantdate = item.ZJHRQ.ObjToDate();
                                        equipment.equipname = item.EQKTX;
                                        equipment.checkresult = item.ZJZJG;
                                        ormClient.SqlSugarClient.Updateable(equipment).
                                            Where(m => m.id == equipment.id).IgnoreColumns(it => it == "id").ExecuteCommand();
                                    }
                                    else
                                    {
                                        scada_equipment equip = new scada_equipment()
                                        {
                                            equipmentid = item.EQUNR,
                                            state = item.ZZTBH,
                                            equipname = item.EQKTX,
                                            plantdate = item.ZJHRQ.ObjToDate(),
                                            checkresult = item.ZJZJG,
                                        };
                                        ormClient.SqlSugarClient.Insertable(equip).IgnoreColumns(it => it == "id").
                                            IgnoreColumns(ignoreNullColumn: true).ExecuteCommand();
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Warn(ex.Message);
                            }
                        }

                    }
                }
            }
        }

        //test
        public void RevceiveTest()
        {
            TestConsumer<EquRoot>((data) =>
            {
                SaveEqument(data);
                return true;
            });
        }

        private Result TestConsumer<T>(Func<T, bool> funReceived)
        {
            try
            {
                try
                {
                    string line;
                    // 从文件读取并显示行，直到文件的末尾 
                    line = File.ReadAllText(@"D:\jsonStr.txt");
                    if(line.Contains("\\")) line = line.Replace("\\", @"$");
                    var msgBody = Regex.Replace(line, @"(\\[^bfrnt\\/'\""])", "\\$1");
                    var data = JsonConvert.DeserializeObject<T>(msgBody);
                    funReceived.Invoke(data);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex);
                    //LoggerHelper.Logger.CreatLogger("Service").Error(ex);
                    //throw;
                }
                System.Diagnostics.Trace.WriteLine("==============TopicExchangeConsumer Start Running ！==============");
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
            finally
            {
                //if (channel != null) channel.Close();
                //if (conn != null) conn.Close();
            }
        }

        public class Equip
        {
            public string EQUNR { get; set; }
        }

        public class EquipRoot
        {
            /// <summary>
            /// 
            /// </summary>
            public List<Equip> EQUILIST { get; set; }
        }
    }
}
